//
//  NetworkTools.swift
//  HMSlender
//
//  Created by 赵少朋赵少朋 on 17/1/19.
//  Copyright © 2017年 ITheima. All rights reserved.
//

import UIKit
import AFNetworking

enum NetWorkToolRequest: String {
    case get = "get"
    case post = "post"
    
}
class NetworkTools: AFHTTPSessionManager {

    
    //单例
    static let sharedNetworkTools:NetworkTools = {
    
        let tool = NetworkTools()
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    ///加载数据
    func loadUrlData(request:NetWorkToolRequest, urlString:String, parameters: Any?, success:@escaping (Any?)->(), failure:@escaping (Any?)->()) {
    
        if request == .get {
            
            self.get(urlString, parameters: parameters, progress: nil, success: { (_, register) in
                
                success(register)
            }, failure: { (_, error) in
                
                failure(error)
            })
        } else {
        
            self.post(urlString, parameters: parameters, progress: nil, success: { (_, register) in
                
                success(register)
            }, failure: { (_, error) in
                
                failure(error)
            })
        }
    }
    //用户授权
    func loadUserAccount(code:String, success:@escaping (Any?)->(), failure:@escaping (Any?)->()) -> Void {
    
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let paramet = [
            
            "client_id": APPKEY,
            "client_secret": APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": REDIRECT_URI
        ]
        
        self.loadUrlData(request: .post, urlString: urlStr, parameters: paramet, success: success, failure: failure)

    }
    
    // MARK: -- 加载用户信息
    func loadUserInfo(userOAuthModel:HMOAuthControllerModel,success:@escaping (Any?)->(), failure:@escaping (Any?)->()) -> Void {
    
        let urlstr = "https://api.weibo.com/2/users/show.json"
        
        let paramet = ["access_token":userOAuthModel.access_token,"uid":userOAuthModel.uid]
        self.loadUrlData(request: .get, urlString: urlstr, parameters: paramet, success: success, failure: failure)
    }
    
    // MARK: -- 加载主页数据
    func loadHomeDataInfo( maxId:Int64, sinceId:Int64,success: @escaping (Any?)->(), failure: @escaping (Any?)->()) -> Void {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        /*
         since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
         max_id
         */
        let parameters = [
            "access_token" : HMOAuthModel.shared.access_token ?? "",
            "since_id": "\(sinceId)",
            "maxId" : "\(maxId)",
        ]
        
        NetworkTools.sharedNetworkTools.loadUrlData(request: NetWorkToolRequest.get, urlString: urlString, parameters: parameters, success:success , failure: failure)
    }
}

// MARK: 发送文字微博和有图片微博
extension NetworkTools {

    // 发布文字微博
    func sendSinaMicroblog(microblogText:String, isFinish:@escaping ((Bool)->())) -> Void {
        
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        
        
        let paramet = ["access_token": HMOAuthModel.shared.access_token,"status":microblogText]
        
        NetworkTools.sharedNetworkTools.loadUrlData(request: NetWorkToolRequest.post, urlString: urlStr, parameters: paramet, success: {(_)->() in
            
            isFinish(true)
            
        }, failure: {(_)->() in
            isFinish(false)
        })
    }
    
    /// 发布图片微博
    func sendSinaMicroblogPicture(microblogText:String, images:[UIImage], success: @escaping (Any?)->(), failure:@escaping(Any?)->()) -> Void {
        
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        let parameter = ["access_token":HMOAuthModel.shared.access_token, "status":microblogText]
//        post(urlStr, parameters: parameter, constructingBodyWith: { (formdata) in
//            
//            //把图片转成二进制
//            let data = UIImagePNGRepresentation(images.first!)!
//            
//            formdata.appendPart(withFileData: data, name: "pic", fileName: "xxxx", mimeType: "application/octet-stream")
//            
//        }, progress: nil, success: progress, failure: progress)
        
        let data = UIImagePNGRepresentation(images.first!)!
        post(urlStr, parameters: parameter, constructingBodyWith: { (formdata) in
            
            formdata.appendPart(withFileData: data, name: "pic", fileName: "xxxx", mimeType: "application/octet-stream")
            
        }, progress: nil, success: { (_, response) in
            success(response)
        }) { (_, error) in
            failure(error)
        }
        
        
    }
}
